var id = getQueryString("id")
$(function () {
    $("#jqGrid").Grid({
        url: '../follow8drecord/list?id=' + id,
        colModel: [
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: '设备编码', name: 'devCode', index: 'DEV_CODE', width: 80, align: 'center'},
            {label: '设备名称', name: 'devName', index: 'DEV_NAME', width: 80},
            {label: '车间', name: 'workshopName', index: 'WORKSHOP_NAME', width: 80},
            {label: '产线', name: 'proLineName', index: 'PRO_LINE_ID', width: 80},
            {label: '工位名称', name: 'workName', index: 'WORK_NAME', width: 80},
            {label: '供应厂家', name: 'devSupply', index: 'DEV_SUPPLY', width: 80},
            // {label: '责任人', name: 'personLia', index: 'PERSON_LIA', width: 80},
            {label: '预防措施', name: 'precaution', index: 'PRECAUTION', width: 80},
            {
                label: '故障发生时间', name: 'happenDate', index: 'HAPPEN_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd')
                }
            },
            {
                label: '计划关闭时间', name: 'closeDate', index: 'CLOSE_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd')
                }
            },
            {
                label: '实际关闭时间', name: 'relCloseDate', index: 'RELCLOSE_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd')
                }
            },
            {
                label: '状态', name: 'recheckStatus', index: 'RECHECK_STATUS', width: 80, formatter: function (value) {
                    return transRecheckStatus(value)
                }
            },
            {label: '创建人员', name: 'createName', index: 'CREATE_USER', width: 80},
            {
                label: '创建时间', name: 'createDate', index: 'CREATE_DATE', width: 80, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd')
                }
            },
            {
                label: '8D附件', name: 'file8d', sortable: false, align: 'center',
                formatter: function (value, col, row) {
                    return row.file8d == null ? "<a>未上传</a>" : "<a id='recordsText' onclick='vm.eyeFile(\"" + row.file8d + "\")'>8D附件</a>";
                }
            },
            {
                label: '预览', name: 'file8d', width: 60, align: 'center',
                formatter: function (value, col, row) {
                    if(row.file8d == null){
                        return "无";
                    }else{
                        value=row.file8d;
                        var png = value.split(".").indexOf(("pdf")) < 0
                        var jpg = value.split(".").indexOf(("png")) < 0
                        var pdf = value.split(".").indexOf(("jpg")) < 0
                        if (png && jpg && pdf) {
                            return "<span>暂不支持</span>"
                        } else {
                            return "<button title='预览' class='btn btn-outline btn-info' onclick='fileCommonHandle(\"" + value + "\")'><i class='fa fa-eye'></i></button>";
                        }
                    }

                }
            },

        ]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        deviceInfoList: [],
        follow8dRecord: {
            remark: '',
            relCloseDate: '',
            closeDate: '',
            personLia: '',
            precaution: '',
            faultDescr: '',
            faultAppear: '',
            happenDate: '',
            workId: '',
            proLineId: '',
            workshopId: '',
            status: '',
            devId: '',
            devName: '',
            devCode: '',
            workName: '',
            workNo: '',
            proLineName: '',
            workshopName: '',
            id: '',
            updateUser: '',
            updateDate: '',
            createUser: '',
            createDate: '',
            recheckStatus: '',
            recheckTime: '',
            recheckUser: '',
            reviewStatus: '',
            reviewTime: '',
            reviewer: '',
            file8d: '',
            file8dName: '',
            delFlag: '',
        },
        ruleValidate: {
            devCode: [
                {required: true, message: '设备编码不能为空', trigger: 'change'}
            ]
        },
        q: {
            devName: '',
            devSupply:''
        },
        picUrl: '',
        reviewStatus: '1',
        recheckStatus: '1'
    },
    methods: {
        query: function () {
            vm.reload();
        },
        ylFile: function (e) {
            var dom = '<iframe frameborder="0" align="left" width="100%" height="100%"\n' +
                'scrolling="auto" marginWidth=0 marginHeight=0 ' +
                ' style="width: 100%;height: 100%" ' +
                'src="' + e + '"></iframe>'

            layer.open({
                type: 1,
                title: "详情",
                closeBtn: 0,
                area: ['60vw', "80vh"],
                offset: '10vh',
                shadeClose: true,
                skin: 'yourclass',
                content: dom
            });
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.follow8dRecord = {
                remark: '',
                relCloseDate: '',
                closeDate: '',
                personLia: '',
                precaution: '',
                faultDescr: '',
                faultAppear: '',
                happenDate: new Date(),
                workId: '',
                proLineId: '',
                workshopId: '',
                status: '',
                devId: '',
                devName: '',
                devCode: '',
                workName: '',
                workNo: '',
                proLineName: '',
                workshopName: '',
                id: '',
                updateUser: '',
                updateDate: '',
                createUser: '',
                createDate: '',
                recheckStatus: '',
                recheckTime: '',
                recheckUser: '',
                reviewStatus: '',
                reviewTime: '',
                reviewer: '',
                file8d: '',
                file8dName: '',
                delFlag: '',
            };
            vm.picUrl = ''
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },

        saveOrUpdate: function (event) {
            if(vm.follow8dRecord.happenDate){
                vm.follow8dRecord.happenDate = vm.GMT2Str(vm.follow8dRecord.happenDate);
            }
            if(vm.follow8dRecord.closeDate){
                vm.follow8dRecord.closeDate = vm.GMT2Str(vm.follow8dRecord.closeDate);
            }
            var url = vm.follow8dRecord.id == (null || '') ? "../follow8drecord/save" : "../follow8drecord/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.follow8dRecord),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../follow8drecord/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../follow8drecord/info/" + id,
                async: false,
                successCallback: function (r) {
                    vm.follow8dRecord = r.follow8dRecord;
                    var url = vm.follow8dRecord.file8d;
                    if (url) vm.picUrl = url.substring((url.lastIndexOf("\/") + 1), url.length);
                }
            });
        },
        reload: function (event) {
            // 构建参数
            var param = {};
            if(vm.q.devName){
                param.devName = vm.q.devName;
            }
            if(vm.q.devSupply){
                param.devSupply = vm.q.devSupply;
            }
            vm.showList = true;
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                devName: '',
                devSupply: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        //显示设备列表-所属设备编码
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.follow8dRecord.devCode = res.devCode;
                        vm.follow8dRecord.devName = res.devName;
                        vm.follow8dRecord.proLineName = res.devProductName;
                        vm.follow8dRecord.proLineId = res.devProductCode;
                        vm.follow8dRecord.workNo = res.devProceNo;
                        vm.follow8dRecord.workName = res.devProceName;
                        vm.follow8dRecord.workshopId = res.devFarm;
                    }
                }
            })
        },
        /**
         * 审核
         */
        review: function () {
            var result = getSelectedRowData("#jqGrid");
            var id = result.id;
            if (id == null) {
                return;
            }
            vm.getInfo(id);

            //判断是否已经审核,已经审核,无法操作
            console.log(vm.follow8dRecord.reviewStatus);

            if (vm.follow8dRecord.reviewStatus == 1) {
                alert('该记录已审核,请勿重复操作!', function (index) {
                    vm.reload();
                    layer.close(index);
                })
                return;
            }
            var param = {id:vm.follow8dRecord.id};
            openWindow({
                title: "审核完成结果",
                area: ['350px', '300px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    param.reviewStatus = parseInt(vm.reviewStatus);
                    Ajax.request({
                        url: '../follow8drecord/review',
                        params: JSON.stringify(param),
                        type: 'POST',
                        contentType: 'application/json',
                        successCallback: function (result) {
                            alert("操作成功",function(index){
                                layer.closeAll();
                                vm.reload();
                            });
                        }
                    })
                }
            })
        },
        /**
         * 复审
         */
        recheck: function () {
            var result = getSelectedRowData("#jqGrid");
            var id = result.id;
            if (id == null) {
                return;
            }
            vm.getInfo(id);
            console.log(result);
            console.log(vm.follow8dRecord.recheckStatus);
            //当记录未关闭时
            if (vm.follow8dRecord.reviewStatus != 1) {
                alert('该记录未审核,请先审核!', function (index) {
                    vm.reload();
                    layer.close(index);
                })
                return;
            }
            if (vm.follow8dRecord.recheckStatus == 1) {
                alert('该记录已复审完,请勿重复操作!', function (index) {
                    vm.reload();
                    layer.close(index);
                })
                return;
            }
            var param = {id:vm.follow8dRecord.id};
            openWindow({
                title: "确认完成结果",
                area: ['350px', '300px'],
                content: jQuery("#recheckLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    param.recheckStatus = parseInt(vm.recheckStatus);
                    Ajax.request({
                        url: '../follow8drecord/recheck',
                        params: JSON.stringify(param),
                        type: 'POST',
                        contentType: 'application/json',
                        successCallback: function (result) {
                            // setTimeout(function () {
                            //     alert()
                            //     location.reload()
                            // }, 1000);
                            alert("操作成功",function(index){
                                layer.closeAll();
                                vm.reload();
                            })
                        }
                    })
                }
            })
        },
        handleBeforeUpload: function() {
            this.$refs.uploadFile.clearFiles()
            this.$Loading.start();
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传格式正确的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleSuccess: function (res, file) {
            this.$Loading.finish();
            iview.Message.success('文件上传成功');
            vm.follow8dRecord.file8d = file.response.url;
            var relName = file.response.name;
            vm.follow8dRecord.file8dName = relName;
            // var url = vm.follow8dRecord.file8d;
            // if (url) vm.picUrl = url.substring((url.lastIndexOf("\/") + 1), url.length);
        },
        eyeFile: function (url) {
            if (url) {
                window.open(url);
            } else {
                alert('还未上传文件');
            }
        },
        GMT2Str: function (gmt) {
            let dateTime = new Date(gmt)
            let year = dateTime.getFullYear()
            let month = dateTime.getMonth() + 1
            let date = dateTime.getDate()
            let hour = dateTime.getHours()
            let minute = dateTime.getMinutes()
            let second = dateTime.getSeconds()
            return year + '-' + this.addZero(month) + '-' + this.addZero(date) + ' ' + this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
        },
        addZero(v) {
            return v < 10 ? '0' + v : v
        }
    }
});
